package toOffer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * <h3>leetcode</h3>
 *
 * @author BigFaceCat
 * @date 2024/3/25 18:02
 * @description <p>两数之和</p>
 */
public class No1 {
    public static void main(String[] args) {
        int[] nums = {2, 7, 11, 15};
        int target = 9;
        for (int i : twoSum(nums, target)) {
            System.out.print(i + " ");
        }
    }

    /**
     * 思路：找target - num[i]在map里有没有存在的
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum(int[] nums, int target) {
        int[] arr = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            arr[1] = i;
            if (map.containsKey(target - nums[i])){
                arr[0] = map.get(target - nums[i]);
                return arr;
            }
            map.put(nums[i], i);
        }

        return null;
    }

    /**
     * 思路：暴力、两层for循环
     *
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum1(int[] nums, int target) {
        int[] arr = new int[2];
        for (int i = 0; i < nums.length; i++) {
            arr[0] = i;
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[j] == target - nums[i]){
                    arr[1] = j;
                    return arr;
                }
            }
        }
        return null;
    }
}
